const router = require('koa-router')();   //路由
const query = require('../utils/query');
const jwt = require('jsonwebtoken');
const tbName = 'user';
const preUrl = '/api/users';
function signIn(userName,pwd){
    return new Promise((resolve,reject)=>{
        query(`select * from ${tbName} where username='${userName}' and userpwd=${pwd}`,function(res){
            if (res.length==0) {
                resolve({
                    code:200,
                    message:'用户名密码错误'
                })
            }else {
                const token = jwt.sign({id:res[0].userid}, 'token', {expiresIn: '15d'})
                resolve({
                    code:200,
                    message:'登录成功',
                    data:{
                        user:res[0],
                        token:token
                    }
                })
            }
        },function(err){
            resolve({
                code:200,
                message:'登录失败',
                data:err
            })
        })
    })
}
router
    .post(`${preUrl}/signIn`,async(ctx,next) =>{ //登录
      //  let data = Token.decrypt(ctx.header.authorization);    token 验证。
        let data = await signIn(ctx.request.body.userName,ctx.request.body.password);
        ctx.body = data;
    })
module.exports = router
